import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Button, Tree, Icon, Spin } from 'antd';
import {
  WeaErrorPage,
  WeaTools,
  WeaInputSearch,
  WeaNewScroll,
  WeaLocaleProvider,
} from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
const TreeNode = Tree.TreeNode;
const { tryCatch } = WeaTools;

@tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@l6617p`}
      msg={
        props.error ||
        getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)
@inject('emailNewStore', 'emailMainStore')
@observer
class ContactsTree extends React.Component {
  static displayName = 'ContactsTree';
  constructor(props) {
    super(props);
    this.prefixCls = 'wea-email-new-contactstree';
  }
  componentDidMount() {
    this.doSearch();
  }
  componentWillReceiveProps() {}
  doSearch = (params = {}) => {
    const {
      emailNewStore: { searchValue: keyword, getContactsTree },
    } = this.props;
    getContactsTree({ keyword, ...params });
  };
  onAdd() {
    const {
      emailMainStore: { onOpenContact },
    } = this.props;
    onOpenContact();
  }
  onExpand(groupId, keys) {
    const {
      emailNewStore: { setState, groupTree },
    } = this.props;
    setState({
      groupTree: toJS(groupTree).map(t => ({
        ...t,
        expandedKeys: groupId === t.groupId ? keys : t.expandedKeys,
      })),
    });
  }
  onSelect = (selectedKeys, e) => {
    const {
      emailNewStore,
      emailNewStore: { setState, focusTagGroup: f, groupTree },
    } = this.props;
    if (
      toJS(groupTree).filter(t => t.groupId.toString() === `${selectedKeys}`)
        .length > 0
    ) {
      return;
    }
    const focusTagGroup = f || 'sendTo_outer';
    const { data } = e.node.props;

    setState({
      [focusTagGroup]: toJS(emailNewStore[focusTagGroup])
        .filter(sendTo => sendTo.id !== data.id)
        .concat([data]),
    });
  };

  onDoubleClick = async (groupId) => {
    const {
      emailNewStore,
      emailNewStore: { focusTagGroup: f },
    } = this.props;
    const { getContactsTreeList } = emailNewStore;
    const focusTagGroup = f || 'sendTo_outer';
    await getContactsTreeList({
      groupid: groupId,
      current: '1',
      addall: 'addall',
      sendtype: focusTagGroup,
    });
    //     this.setState(
    //      {
    //        [focusTagGroup]:
    //        toJS(emailNewStore[focusTagGroup]).concat(res.contactList),
    //    });
  };

  onLoadData = async (treeNode) => {
    const {
      props: {
        data: { current, groupId: groupid },
      },
    } = treeNode;
    const {
      emailNewStore: { searchValue: keyword, getContactsTreeList },
    } = this.props;
    const res = await getContactsTreeList({
      keyword,
      current: current + 1,
      groupid,
    });
    return res;
  };
  getTree(tree) {
    const {
      groupId,
      groupName,
      count,
      contactList = [],
      current,
      totalPage,
      expandedKeys = [],
    } = tree;

    const {
      emailNewStore: { contactsTreeListloadingId, contactsTreeListLoading },
    } = this.props;
    const treeNodes = contactList.map(item => (
      <TreeNode
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_TreeNode@fyivuv@${item.id}`}
        key={item.id}
        title={item.name}
        data={item}
        isLeaf={true}
      />
    ));
    const hasMore = current < totalPage && contactList.length > 0;
    hasMore &&
      treeNodes.push(
        <TreeNode
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_TreeNode@0s2d7q@${groupId}`}
          key={`${groupId}`}
          className={`${this.prefixCls}-tree-more-wrap`}
          title={
            /* eslint-disable */
            <p
              className={`${this.prefixCls}-tree-more`}
              onClick={(e) => {
                !(
                  contactsTreeListLoading &&
                  contactsTreeListloadingId === groupId
                ) &&
                  hasMore &&
                  this.onLoadData({ props: { data: tree } });
                e.stopPropagation && e.stopPropagation();
                e.preventDefault && e.preventDefault();
                e.nativeEvent && e.nativeEvent.preventDefault();
              }}
            >
              {contactsTreeListLoading &&
              contactsTreeListloadingId === groupId ? (
                <Icon
                  ecId={`${
                    (this && this.props && this.props.ecId) || ""
                  }_Icon@9hu6xo@loading`}
                  type="loading"
                />
              ) : hasMore ? (
                <span>
                  {getLabel(17499, "更多")} <i className="icon-coms-down" />
                </span>
              ) : null}
            </p>
            /* eslint-enable */
          }
          isLeaf={true}
        />,
      );
    return (
      <div className={`${this.prefixCls}-tree`}>
        <Tree
          ecId={`${(this && this.props && this.props.ecId) || ''}_Tree@lcg970`}
          expandedKeys={toJS(expandedKeys)}
          selectedKeys=""
          loadData={this.onLoadData}
          onSelect={this.onSelect}
          onDoubleClick={e =>
            e.indexOf('@') === -1 && this.onDoubleClick(groupId)
          }
          onExpand={keys => this.onExpand(groupId, keys)}
        >
          <TreeNode
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_TreeNode@3x6rxq`}
            data={tree}
            key={groupId}
            title={`${groupName} (${count})`}
            isLeaf={count <= 0}
          >
            {treeNodes}
          </TreeNode>
        </Tree>
      </div>
    );
  }
  render() {
    const {
      className,
      emailNewStore: { searchValue, groupTree, setState, contactsTreeLoading },
    } = this.props;
    return (
      <div className={`${this.prefixCls} ${className}`}>
        <div className={`${this.prefixCls}-search`}>
          <span
            style={{ margin: '0 9px' }}
            title={getLabel(83093, '自定义联系人')}
          >
            {getLabel(83093, '自定义联系人')}
          </span>
          <WeaInputSearch
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaInputSearch@n1ejzl`}
            value={searchValue}
            style={{ width: 124 }}
            onSearchChange={v => setState({ searchValue: v })}
            onSearch={() => this.doSearch()}
          />
          <Button
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Button@1zrlfq`}
            className={`${this.prefixCls}-search-add`}
            title={getLabel(81294, '新建联系人')}
            onClick={() => this.onAdd(searchValue)}
          >
            <Icon
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Icon@r2tql7`}
              type="plus"
            />
          </Button>
        </div>
        <div className={`${this.prefixCls}-trees`}>
          <Spin
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Spin@tj8b14`}
            spinning={contactsTreeLoading}
          >
            <WeaNewScroll
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaNewScroll@lfs2as`}
              height="100%"
            >
              {toJS(groupTree).map(t => this.getTree(t))}
            </WeaNewScroll>
          </Spin>
        </div>
      </div>
    );
  }
}

export default ContactsTree;
